package com.tc.zigbee.mt;

import java.io.IOException;
import java.io.InputStream;

import com.tc.gateway.ErrorListener;
import com.tc.gateway.tunnel.TunnelOutput;
import com.tc.serial.SerialStream;
import com.tc.zigbee.mt.income.IncomeMessage;

public class IncomingMessageReader extends Thread {
	SerialStream serial;
	MessageListener listener;
	TunnelOutput tunnelServer;
	ErrorListener errorListener;
	public void setErrorListener(ErrorListener errorListener) {
		this.errorListener = errorListener;
	}

	public IncomingMessageReader(
			final SerialStream s, 
			MessageListener l, TunnelOutput ts
			) {
		super("readerThread");
		listener = l;
		serial = s;
		tunnelServer = ts;
	}

	@Override
	public void run() {
		InputStream in = serial.getInputStream();
		
		while (true) {
	
				try {
					MtCommand mc = new MtCommand();
					byte[] f;
					try {
						f = mc.read(in);
					} catch (IOException e) {
						e.printStackTrace();
						if(this.errorListener != null){
							errorListener.onException(e);
						}
						return;
					}
					IncomeMessage im = IncomeMessageParser.parse(mc);
					if(im != null){
						listener.onMessage(im);
						if(tunnelServer != null)
							tunnelServer.write(f, 0, f.length);
					}
				} catch (Throwable e) {
					
					e.printStackTrace();
				}
				
			
		}
	}

}
